import RedLock, { Lock } from 'redlock';
import { RedisClient } from './index';

const opts = {
  retryCount: 10, // Maximum number of retries
  retryDelay: 100, // Retry interval
  retryJitter: 200, // Improve performance
};

export function createRedLock(client: RedisClient) {
  return new RedLock([client], opts);
}

export function getLock(redlock: RedLock, resource: string, ttl: number = 1000): Promise<Lock | null> {
  return new Promise((resolve) => {
    redlock.lock(resource, ttl).then((lock: Lock) => {
      resolve(lock);
    }).catch(() => {
      resolve(null);
    });
  });

}
